package com.anxin.security.jwt;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenProvider {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Value("${jwt.expiration}")
    private int jwtExpirationInMs;

    private JWTSigner getSigner() {
        return JWTSignerUtil.hs256(jwtSecret.getBytes());
    }

    public String generateToken(String username) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);

        Map<String, Object> payload = new HashMap<>();
        payload.put("sub", username);
        payload.put("iat", now.getTime());
        payload.put("exp", expiryDate.getTime());

        return JWTUtil.createToken(payload, getSigner());
    }

    /**
     * 从JWT中获取用户名
     *
     * @param token
     * @return
     */
    public String getUsernameFromJWT(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        return jwt.getPayload("sub").toString();
    }

    /**
     * 验证JWT
     * 验证 Token 是否合法、未过期
     * @param token
     * @return
     */
    public boolean validateToken(String token) {
        try {
            JWT jwt = JWTUtil.parseToken(token);
            return jwt.verify(getSigner());
        } catch (Exception e) {
            return false;
        }
    }
}
